package huoye.shops.base;


import android.text.TextUtils;

import com.codeideology.android.log.LogUtils;
import com.codeideology.android.utils.DigitalUtils;
import com.codeideology.android.utils.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by user on 2016/11/29.
 */

public class Dig implements Interceptor {
    public static final String TAG = Dig.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();


        if (canInjectIntoBody(request)) {
            FormBody.Builder formBodyBuilder = new FormBody.Builder();

            String postBodyString = bodyToString(request.body());
            Map<String, String> map = getParam(postBodyString);
          //  map.put("uid", UserManager.getInstance().getUid());
            String requsetStr = StringUtils.getRequestParam(map);
            String deviceHash   = StringUtils.sort(UserManager.getInstance().getDeviceHash()).substring(0,20);
            String sig = DigitalUtils.md5(requsetStr+ DigitalUtils.md5(deviceHash));
            sig = sig.substring(sig.length() - 16);

       /*     formBodyBuilder.add("sig",  sig);
            formBodyBuilder.add("uid", UserManager.getInstance().getUid());*/


            RequestBody formBody = formBodyBuilder.build();
            postBodyString += ((postBodyString.length() > 0) ? "&" : "") +  bodyToString(formBody);
            requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString));
            LogUtils.d("post", postBodyString);
        }

        request = requestBuilder.build();
        return chain.proceed(request);
    }

    public TreeMap<String, String> getParam(String postBodyString) {
        String[]values = postBodyString.split("&");
        TreeMap<String, String> map = new TreeMap<>();
        if(values.length > 0) {
            for (int i = 0; i < values.length;i++) {
                String[] key = values[i].split("=");
                if(key.length == 2) {
                    map.put(key[0], StringUtils.getURLDecoderString(key[1]));
                }
            }
        }

        return map;
    }




    private static String bodyToString(final RequestBody request){
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if(copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        }
        catch (final IOException e) {
            return "did not work";
        }
    }
    private boolean canInjectIntoBody(Request request) {
        if (request == null) {
            return false;
        }
        if (!TextUtils.equals(request.method(), "POST")) {
            return false;
        }
        RequestBody body = request.body();
        if (body == null) {
            return false;
        }
        MediaType mediaType = body.contentType();
        if (mediaType == null) {
            return false;
        }
        if (!TextUtils.equals(mediaType.subtype(), "x-www-form-urlencoded")) {
            return false;
        }
        return true;
    }
}
